﻿''' <summary>
''' 制冷相关实时数据
''' </summary>
''' <remarks></remarks>
Public Class FrmCcapRealData


    ''' <summary>
    ''' 端口列表
    ''' </summary>
    ''' <remarks></remarks>
    Private ports As Hashtable
    ''' <summary>
    ''' 项目编号
    ''' </summary>
    ''' <remarks></remarks>
    Private ProjectId As String

    ''' <summary>
    ''' 数据报警事件
    ''' </summary>
    ''' <remarks></remarks>
    Public Event PalyAlarmEvent As EventHandler
    '''' <summary>
    '''' 默认构造函数
    '''' </summary>
    '''' <remarks></remarks>
    'Public Sub New()
    '    ' This call is required by the designer.
    '    InitializeComponent()

    '    ' Add any initialization after the InitializeComponent() call.
    '    Me.ProjectId = "100"
    '    Init()
    'End Sub

    Public Shared WidthReal As Integer = 870

    Public Shared WidthInit As Integer = 870

    Protected Overrides Sub OnSizeChanged(ByVal e As System.EventArgs)
        MyBase.OnSizeChanged(e)

        WidthReal = Me.Width

        RaiseEvent WidthChange(Me, EventArgs.Empty)
    End Sub

    ''' <summary>
    ''' 使用项目ID进场初始化
    ''' </summary>
    ''' <param name="projectId">项目编号</param>
    ''' <remarks></remarks>
    Public Sub New(ByVal projectId As String)
        InitializeComponent()
        Me.ProjectId = projectId
        AddHandler Me.WidthChange, AddressOf UpdateWidth
        Init()
    End Sub
    ''' <summary>
    ''' 实时数据
    ''' </summary>
    ''' <remarks></remarks>
    Private WithEvents RealData As CcapRealData

    ''' <summary>
    ''' 初始化
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Init()

        Try
            RealData = New CcapRealData(Me.ProjectId)

            '' 绑定事件
            AddHandler RealData.NewDataEvent, AddressOf RefreshPort
            AddHandler Me.PalyAlarmEvent, AddressOf NoticeAlarmSound

            InitCompressorSet()
        Catch
            msg.ShowError("加载配置错误")
            Close()
        End Try
    End Sub


    Sub UpdateWidth(ByVal sender As Object, ByVal e As EventArgs)
        For Each ctl As Control In Me.Controls
            If (TypeOf ctl Is GroupBox) Then
                ctl.Width = 830 + WidthReal - WidthInit

                For Each ctll As Control In ctl.Controls

                    If (TypeOf ctll Is DeviceGlobal) Then
                        ctll.Width = 817 + WidthReal - WidthInit
                        Continue For
                    End If

                    If (TypeOf ctll Is DevGroupCaption) Then
                        ctll.Width = 817 + WidthReal - WidthInit
                        Continue For
                    End If

                    If (TypeOf ctll Is DeviceMultiple) Then
                        ctll.Width = 817 + WidthReal - WidthInit
                        Continue For
                    End If

                    If (TypeOf ctll Is DeviceSingle) Then
                        ctll.Width = 817 + WidthReal - WidthInit
                        Continue For
                    End If

                    If (TypeOf ctll Is DeviceGroup) Then

                        ctll.Width = 817 + WidthReal - WidthInit
                        Dim ctdg As DeviceGroup = CType(ctll, DeviceGroup)
                        For Each ctlll As Control In ctdg.pnlDevs.Controls
                            If (TypeOf ctlll Is DeviceItem) Then
                                ctlll.Width = 675 + WidthReal - WidthInit
                            End If

                        Next

                        Continue For
                    End If

                Next
            End If
        Next
    End Sub

    Private bLoadFailured As Boolean = False

    Public Sub InitCompressorSet()
        '' 设置groupbox坐标
        Me.GroupBoxLocationY = 5
        ports = New Hashtable()

        Dim dal As CcapCompressorSetItemService = New CcapCompressorSetItemService
        Dim ds As DataSet = Nothing


        Try
            CreateGlobalPorts()
            ds = dal.GetCompressorSets(ProjectId)
            ''Id, DevId, csName,csType, csCount, csNetId
            If (ds IsNot Nothing AndAlso ds.Tables(0).Rows.Count > 0) Then
                For Each dr As DataRow In ds.Tables(0).Rows
                    '' csType:0  冷凝机组 
                    '' csType:1  并联机组
                    If (CInt(dr(3)) = 0) Then
                        CreateDevice(CInt(dr(0)), CInt(dr(5)), False)
                    ElseIf (CInt(dr(3)) = 1) Then
                        CreateDevice(CInt(dr(0)), CInt(dr(5)), True)
                    End If
                Next
            End If



        Catch ex As ArgumentException
            bLoadFailured = True
            System.Windows.Forms.MessageBox.Show("系统端口配置错误！" + Environment.NewLine + "请检查系统端口配置。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)

        Catch ex As Exception
            bLoadFailured = True
            System.Windows.Forms.MessageBox.Show("系统错误！" + Environment.NewLine + "请检查系统端口配置，数据库运行是否正常。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
        End Try

        Me.btnClose.Location = New Point(Me.btnClose.Location.X, Me.GroupBoxLocationY + 11)
        Me.Size = New Size(Me.Width, Me.GroupBoxLocationY + 20 + btnClose.Size.Height + 26)
    End Sub



    Private Sub CreateGlobalPorts()
        Dim iTop As Integer = 10
        Dim iLeft As Integer = 3
        Dim gp As GroupBox = New GroupBox()
        Dim gl As DeviceGlobal = New DeviceGlobal(Me.ProjectId)
        If (gl.GetPorts.Count > 0) Then
            gl.Location = New Point(iLeft, iTop)
            iTop += gl.Height
            gp.Controls.Add(gl)

            'AddHandler Me.WidthChange, AddressOf gl.UpdateWidth

            Me.AddItemToPorts(gl.GetPorts())

            gp.Height = iTop + GroupBoxExtendHeight
            gp.Width = gl.Width + GroupBoxExtendWidth

            gp.Location = New Point(GroupBoxLocationX, GroupBoxLocationY)
            gp.BackColor = Color.FromKnownColor(KnownColor.GradientActiveCaption)
            GroupBoxLocationY += gp.Height + GroupBoxExtendHeight
            Me.Controls.Add(gp)
        End If


    End Sub

    ''' <summary>
    ''' 创建机组
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CreateDevice(ByVal csId As Integer, ByVal devId As Integer, Optional ByVal bMulti As Boolean = False)

        Dim iTop As Integer = 20
        Dim iLeft As Integer = 3

        Dim gp As GroupBox = New GroupBox()

        '' 显示caption
        Dim gc As DevGroupCaption = New DevGroupCaption(csId)
        gc.Location = New Point(iLeft, iTop)
        iTop += gc.Height
        gp.Controls.Add(gc)

        If (bMulti) Then
            '' 压缩机组
            Dim dm As DeviceMultiple = New DeviceMultiple(csId, devId)
            dm.Location = New Point(iLeft, iTop)

            If (dm.GetPorts().Count > 0) Then
                iTop += dm.Height
                gp.Controls.Add(dm)
                Me.AddItemToPorts(dm.GetPorts())
            End If

        Else
            Dim dm As DeviceSingle = New DeviceSingle(csId, devId)
            dm.Location = New Point(iLeft, iTop)
            If (dm.GetPorts().Count > 0) Then
                iTop += dm.Height
                gp.Controls.Add(dm)

                Me.AddItemToPorts(dm.GetPorts())
            End If

        End If

        '' 压缩机
        Dim cp As DeviceGroup = New DeviceGroup(csId, devId, DeviceTypes.Compressor)
        If (cp.GetPorts().Count > 0) Then
            cp.Location = New Point(iLeft, iTop)
            iTop += cp.Height

            gp.Controls.Add(cp)
            Me.AddItemToPorts(cp.GetPorts())
        End If


        '' 冷凝器
        Dim ce As DeviceGroup = New DeviceGroup(csId, devId, DeviceTypes.Condenser)
        If (ce.GetPorts().Count > 0) Then
            ce.Location = New Point(iLeft, iTop)
            iTop += ce.Height

            gp.Controls.Add(ce)
            Me.AddItemToPorts(ce.GetPorts())
        End If


        ' 冷风机
        Dim ac As DeviceGroup = New DeviceGroup(csId, devId, DeviceTypes.AirCooler)
        If ac.GetPorts().Count > 0 Then
            ac.Location = New Point(iLeft, iTop)
            iTop += ac.Height

            gp.Controls.Add(ac)
            Me.AddItemToPorts(ac.GetPorts())
        End If


#If DEBUG Then
        System.Diagnostics.Debug.Print("Create Device End Add Prots to hashTable csID:{0}   bordId{1} Multiple{2}", csId, devId, bMulti)
#End If
        gp.Text = ""
        gp.Height = iTop + GroupBoxExtendHeight
        gp.Width = ac.Width + GroupBoxExtendWidth

        gp.Location = New Point(GroupBoxLocationX, GroupBoxLocationY)
        gp.BackColor = Color.FromKnownColor(KnownColor.GradientActiveCaption)
        GroupBoxLocationY += gp.Height + GroupBoxExtendHeight
        iTop += GroupBoxExtendHeight
        Me.Controls.Add(gp)

    End Sub

    ''' <summary>
    ''' 添加端口到ports列表中
    ''' </summary>
    ''' <param name="hs">包含端口的hashtable</param>
    ''' <remarks></remarks>
    Private Sub AddItemToPorts(ByVal hs As Hashtable)
        Try
            For Each key As Integer In hs.Keys
                Dim ps As PortStatus = CType(hs(key), PortStatus)
#If DEBUG Then

                System.Diagnostics.Debug.Print(String.Format("Key:{0}   PortName:{1}     PortNumber{2}", key, ps.PortName, ps.PortID))
#End If
                ports.Add(key, hs(key))

            Next
        Catch ex As Exception

        End Try

    End Sub

#Region "GroupBoxSetting"

    ''' <summary>
    ''' Groupbox 的y坐标
    ''' </summary>
    ''' <remarks></remarks>
    Private GroupBoxLocationY As Integer = 10

    ''' <summary>
    '''  Groupbox 的X坐标
    ''' </summary>
    ''' <remarks></remarks>
    Private GroupBoxLocationX As Integer = 10

    ''' <summary>
    ''' GroupBox 的扩展高度
    ''' </summary>
    ''' <remarks></remarks>
    Private GroupBoxExtendHeight As Integer = 5

    ''' <summary>
    ''' GroupBox 的扩展宽度
    ''' </summary>
    ''' <remarks></remarks>
    Private GroupBoxExtendWidth As Integer = 5
#End Region


    ''' <summary>
    ''' 刷新界面
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub RefreshPort(ByVal sender As Object, ByVal e As EventArgs)

        Try
            Dim realData As CcapRealData = CType(sender, CcapRealData)
            realData.RefreshProcessing = True '正在刷新工程数据主窗口

            If (e Is Nothing) Then
                ''没有配置
                SetReadErrorLableVisible(True)
            Else
                ''刷新所有控件值
                SetReadErrorLableVisible(False)

                refreshControlval(realData)
            End If


            realData.RefreshProcessing = False  '刷新工程数据主窗口结束
        Catch ex As Exception
            Debug.Print("newdata exception\n")
        End Try
    End Sub

    ''' <summary>
    ''' 通知报警声音
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub NoticeAlarmSound(ByVal sender As Object, ByVal e As System.EventArgs)
        PlayAlarmSound()
    End Sub

    ''' <summary>
    ''' 播放报警声音
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub PlayAlarmSound()
        Dim fileName As String
        fileName = g_AlarmSoundFile
        If fileName = "" OrElse Not System.IO.File.Exists(fileName) Then
            Exit Sub
        End If
        '  My.Computer.Audio.Play(fileName, AudioPlayMode.Background)
        TBCC.Utility.Media.PlayerHelper.Instance().Play(fileName)
    End Sub

    ''' <summary>
    ''' 声明刷新控件处理委托
    ''' </summary>
    ''' <remarks></remarks>
    Private Delegate Sub refreshControlvalhandler(ByVal sender As System.Object)

    ''' <summary>
    ''' 刷新界面
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub refreshControlval(ByVal sender As Object)
        If Me.InvokeRequired Then
            Dim d As New refreshControlvalhandler(AddressOf _refreshControlval)
            Me.Invoke(d, New Object() {sender})
        Else
            _refreshControlval(sender)
        End If
    End Sub

    ''' <summary>
    ''' 刷新界面数据
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub _refreshControlval(ByVal sender As System.Object)
        ''==========================
        '' 刷新界面数据
        Dim realData As CcapRealData = CType(sender, CcapRealData)
#If DEBUG Then
        System.Diagnostics.Debug.Print(" start Refresh ControlVal At: {0}", DateTime.Now.ToLongTimeString)
#End If
        If ports.Count > 0 AndAlso realData.RealDataList.Count > 0 Then
            For Each item As CcapDataItem In realData.RealDataList
                For Each key As Integer In ports.Keys
                    Dim ps As PortStatus = CType(ports(key), PortStatus)
                    Dim ibord As Integer
                    Dim iport As Integer
                    ibord = Math.Floor(key / 100)
                    iport = ps.PortID
                    '' 只有在同一个板子上时才进行更新数据
                    If (ibord = item.BordId) Then
                        Select Case ps.PortType
                            Case PortTypes.Temperature
                                '' 温度
                                '' 需要检查端口的数值，报警，激活
                                ps.Value = item.GetAIValue(iport)
                                ps.PortAlarmStatus = item.GetAlAlarm(iport)
                            Case PortTypes.Normal
                                '' 文字报警
                                '' 直接检查状态，报警，激活
                                ps.PortStatus = item.GetPortStatus(iport)
                                ps.PortAlarmStatus = item.GetPortAlarm(iport)

                            Case Else
                                ' 其他情况按照Normal处理
                                ps.PortStatus = item.GetPortStatus(iport)
                                ps.PortAlarmStatus = item.GetPortAlarm(iport)
                        End Select

                        '' 检测报警
                        If ps.PortAlarmStatus = PortAlarmEnums.Alarm Then
                            RaiseEvent PalyAlarmEvent(Nothing, New EventArgs())
                        End If
                    End If

                Next key
            Next item
        End If

#If DEBUG Then
        System.Diagnostics.Debug.Print(" End Refresh ControlVal At: {0}", DateTime.Now.ToLongTimeString())
#End If
    End Sub

    ''' <summary>
    ''' 设置界面ports读取数据失败
    ''' </summary>
    ''' <param name="bError"></param>
    ''' <remarks></remarks>
    Private Sub SetReadErrorLableVisible(ByVal bError As Boolean)
        If (bError = True) Then
            For Each key As Integer In ports.Keys
                Dim ps As PortStatus = CType(ports(key), PortStatus)
                ps.UpdateValue(PortStatuEnums.Unknown, PortAlarmEnums.Unknown)
            Next
        End If
    End Sub


    ''' <summary>
    ''' 关闭窗体时，是否后台传输数据线程
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
        If Me.RealData IsNot Nothing Then
            Me.RealData.StopDataTransfer()
        End If
        MyBase.OnClosing(e)
    End Sub

    ''' <summary>
    ''' 开始传输数据
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub StartDataTransfer()
        Me.RealData.StartDataTransfer()
    End Sub

    ''' <summary>
    ''' 结束数据传输
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub StopDataTransfer()
        Me.RealData.StopDataTransfer()
    End Sub

    ''' <summary>
    ''' 界面加载时执行
    ''' </summary>
    ''' <remarks>
    ''' 开启同步数据
    ''' </remarks>
    Private Sub FrmCcapRealData_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        If (bLoadFailured) Then
            'Me.CancelButton.PerformClick()
            Exit Sub
        Else
            If Me.ports.Count = 0 Then
                '  System.Windows.Forms.MessageBox.Show("未配置制冷设备。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
                ' Me.CancelButton.PerformClick()
                Exit Sub
            End If
        End If
        StartDataTransfer()
    End Sub

    Public Event WidthChange As EventHandler

    Private Sub FrmCcapRealData_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown
        WidthReal = Me.Width
        RaiseEvent WidthChange(Me, EventArgs.Empty)
    End Sub
End Class